//
//  TMGFlowViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/13.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGBootomGoldDetailController.h"
#import "TMMenuControl.h"
#import "TMGUserTableViewCell.h"
#import "TMGFlowMoreTableViewCell.h"
#import "TMGBuyGoldViewController.h"
@interface TMGBootomGoldDetailController ()
@property(nonatomic, strong) NSArray                               *titleArray;
@property(nonatomic, strong) STSegementButton                      *segementButton;
@property(nonatomic, strong) UIView                                *topView;
@property(nonatomic, strong) NSArray<STTableEasyModel*>            *productArray;
@property(nonatomic, strong) NSMutableArray                               *userArray;
@property(nonatomic, strong) NSArray                               *moreArray;

@property(nonatomic, strong) TMGProductDetailModel                     *detailModel;
@end

@implementation TMGBootomGoldDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.model.name;
    _titleArray = @[@"产品详情",@"购买人数",@"更多"];
    _titleArray = @[@"产品详情",@"购买人数"];
    [self configSubView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, self.topView.bottom, UIScreenWidth, UIScreenHeight - 50 - self.topView.bottom);
    
    [self.tableView registerClass:[TMGUserTableViewCell class] forCellReuseIdentifier:@"userCell"];
    [self.tableView registerClass:[TMGFlowMoreTableViewCell class] forCellReuseIdentifier:@"moreCell"];
    [self sendGoodDetailReqeust];
    [self sendGoodPeopleBuyReqeust];
    
    // Do any additional setup after loading the view.
}
- (void)reloadData{
    NSString * free = [NSString stringWithFormat:@"%@元/克",self.detailModel.fee];
    
    NSString * saleFree = [NSString stringWithFormat:@"%@元/克",self.detailModel.fee_sale];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    NSString * buyStratr = [NSString stringWithFormat:@"%@元起购",
                            @(self.detailModel.buy_start.integerValue)];
    
    self.productArray = @[
                          [[STTableEasyModel alloc] initWithTextString:@"黄金品种" detailString:@"上海黄金交易所"],
                          [[STTableEasyModel alloc] initWithTextString:@"产品说明" detailString:@"投资期间不可转让、赎回"],
                          [[STTableEasyModel alloc] initWithTextString:@"买入手续费" detailString:free],
                          [[STTableEasyModel alloc] initWithTextString:@"卖出手续费" detailString:saleFree],
                          [[STTableEasyModel alloc] initWithTextString:@"收益构成" detailString:rate],
                          [[STTableEasyModel alloc] initWithTextString:@"金价上涨收益" detailString:@"卖出根据实时金价计算"],
                          [[STTableEasyModel alloc] initWithTextString:@"购买截止" detailString:@"随时买卖"],
                          [[STTableEasyModel alloc] initWithTextString:@"买入期限" detailString:self.detailModel.deadline],
                          [[STTableEasyModel alloc] initWithTextString:@"起购金额" detailString:@(buyStratr.integerValue).description],
                          [[STTableEasyModel alloc] initWithTextString:@"单次购买上限"
                                                          detailString:[NSString stringWithFormat:@"%@元",self.detailModel.buy_limit]],
                          [[STTableEasyModel alloc] initWithTextString:@"风险等级" detailString:@"不保本"]];
    
    
    self.moreArray = @[@{@"title":@"买的真的是黄金吗",
                         @"subtitle":@"黄金来源于国家级交易市场",
                         @"content":@"黄金口袋通过XX银行在上海黄金交易所(中国人民银行组建的黄金交易国家级市场) 开立了黄金交易账户，保证所有购买的黄金都是国家认可的万足金(Au9999) 实物黄金"},
                       @{@"title":@"黄金口袋收益怎么样?",@"subtitle":@"",@"content":@"近10年金价的年均涨幅约为8%，在黄金口袋投资黄金中，您不仅能够获得金价涨跌的权益，我们还未您额外提供了最高的6.0%的利息。在黄金口袋购入黄金，您相当于获得8% + 最高6%的双重预计黄金收益率"},
                       @{@"title":@"如果借金企业到期不还怎么办?",@"subtitle":@"只借给信用良好的借金企业",@"content":@"近10年金价的年均涨幅约为8%，在黄金口袋投资黄金中，您不仅能够获得金价涨跌的权益，我们还未您额外提供了最高的6.0%的利息。在黄金口袋购入黄金，您相当于获得8% + 最高6%的双重预计黄金收益率"}];
    [self.tableView reloadData];
}

#pragma mark --subView
- (void)configSubView{
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, [TMUtils navgationBarBootom], UIScreenWidth, 100)];
    topView.backgroundColor = [UIColor whiteColor];
    UIImageView * bannerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    [self.view addSubview:topView];
    bannerImageView.backgroundColor = TM_orangeColor;
    bannerImageView.userInteractionEnabled = YES;
    [topView addSubview:bannerImageView];
    
    NSString * rate = self.detailModel.year_rate_from;
    if (self.detailModel.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.detailModel.year_rate_from,self.detailModel.year_rate_to];
    }
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, 200, 80)
                                                     text:[NSString stringWithFormat:@"%@%%\n预计黄金收益率",rate]
                                                textColor:[UIColor whiteColor]
                                                     font:26
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    titleLable.centerX = UIScreenWidth / 2;
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"预计黄金收益率" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    [bannerImageView addSubview:titleLable];
    TMMenuControl *  suishiControl = [self controlWithValue:self.detailModel.deadline name:@"买入期限"];
    suishiControl.left = 0;
    suishiControl.top = bannerImageView.bottom;
    [topView addSubview:suishiControl];
    
    TMMenuControl *  baobenControl = [self controlWithValue:@"非保本型" name:@"风险提示"];
    baobenControl.left = suishiControl.right;
    baobenControl.top = bannerImageView.bottom;
    [NSString lableAutoAdjustWitdhWithLabel:baobenControl.nameLable];
    baobenControl.nameLable.centerX = baobenControl.width / 2;
    UIImageView * why = [[UIImageView alloc] initWithFrame:CGRectMake(baobenControl.nameLable.right + 10, baobenControl.nameLable.top, 10, 10)];
    why.image = [UIImage imageNamed:@"问号"];
    why.centerY = baobenControl.nameLable.centerY;
    [baobenControl addSubview:why];
    [topView addSubview:baobenControl];
    
    NSString * buyStratr = [NSString stringWithFormat:@"%@元起购",
                            @(self.detailModel.buy_start.integerValue)];
    TMMenuControl *  buyControl = [self controlWithValue:@(buyStratr.integerValue).description name:@"起购金额"];
    buyControl.left = baobenControl.right;
    buyControl.top = bannerImageView.bottom;
    [topView addSubview:buyControl];
    
    UIView * grawView = [[UIView alloc] initWithFrame:CGRectMake(0, buyControl.bottom, UIScreenWidth, 10)];
    grawView.backgroundColor = TM_backgroundColor;
    [topView addSubview:grawView];
    __weak typeof(self) weakSelf =  self;
    self.segementButton = [[STSegementButton alloc] initWithFrame:CGRectMake(0, grawView.bottom, UIScreenWidth, 59)
                                                         andTitle:_titleArray handle:^(STSegementButton *sender) {
                                                             [weakSelf.tableView reloadData];
                                                         }];
    self.segementButton.backgroundColor = [UIColor whiteColor];
    self.segementButton.lineSelectedColor = TM_orangeColor;
    self.segementButton.butTitleSelectedColor = TM_orangeColor;
    self.segementButton.butTitleColor = TM_secendTextColor;
    self.segementButton.lineColor = [UIColor whiteColor];
    self.segementButton.cureentIndex = 0;
    self.segementButton.autoMoveWithClic = YES;
    [TMGProductDataController sendPeopleAllNumWithGid:self.model.goodiID.description handle:^(NSString *num) {
        if (num.description.length) {
            UIButton * button = [self.segementButton buttonWirhIndex:1];
            [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateNormal];
            [button setTitle:[NSString stringWithFormat:@"购买人数%@位",num] forState:UIControlStateSelected];
        }
    }];
    [topView addSubview:self.segementButton];
    
    self.topView = topView;
    topView.height = self.segementButton.bottom;
    
    [self configBootomView];
}
- (TMMenuControl*)controlWithValue:(NSString*)value name:(NSString*)name{
    TMMenuControl * suishiControl = [[TMMenuControl alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 3, 60) value:value name:@"买入期限" showLine:YES];
    [suishiControl addTarget:self action:@selector(onSlectedControl:) forControlEvents:UIControlEventTouchUpInside];
    suishiControl.valueLable.attributedText = nil;
    suishiControl.valueLable.text = value;
    suishiControl.nameLable.textColor = TM_secendTextColor;
    suishiControl.nameLable.text = name;
    return suishiControl;
}
- (void)configBootomView{
    __weak typeof(self) weakSelf =  self;
    STButton * inButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth/2, 50)
                                                     title:@"流动金转入"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:FlatOrange
                                           backgroundImage:nil
                                                     image:nil];
    inButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [inButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedFlowInButton];
    }];
     inButton.bottom = UIScreenHeight;
    [self.view addSubview:inButton];
    
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(UIScreenWidth/2, 0, UIScreenWidth/2, 50)
                                                     title:@"立即购买"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:TM_orangeColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedBuyButton];
    }];
    [self.view addSubview:buyButton];
    buyButton.bottom = UIScreenHeight;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.segementButton.cureentIndex == 0) {
        return self.productArray.count;
    }
    if (self.segementButton.cureentIndex == 1) {
        return self.userArray.count;
    }
    if (self.segementButton.cureentIndex == 2) {
        return self.moreArray.count;
    }
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.segementButton.cureentIndex == 3) {
        return [TMGFlowMoreTableViewCell cellHeight];
    }
    if (self.segementButton.cureentIndex == 2) {
        return [TMGFlowMoreTableViewCell cellHeight];
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.segementButton.cureentIndex == 0) {
        static NSString * reuseIdentifier =  @"cell";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
            
        }
        cell.textLabel.textColor = TM_secendTextColor;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
        cell.detailTextLabel.textColor = TM_firstTextColor;
        STTableEasyModel * model = self.productArray[indexPath.row];
        cell.textLabel.text = model.textString;
        cell.detailTextLabel.text = model.detailString;
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    if (self.segementButton.cureentIndex == 1) {
        TMGUserTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"userCell"];
        cell.model = self.userArray[indexPath.row];
        return cell;
    }
    if (self.segementButton.cureentIndex == 2) {
        TMGFlowMoreTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:@"moreCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary * dic = self.moreArray[indexPath.row];
        cell.titleLable.text = dic[@"title"];
        cell.subTitleLabel.text = dic[@"subtitle"];
        cell.desLabel.text = dic[@"content"];
        return cell;
        
    }
    return nil;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSlectedControl:(TMMenuControl*)sender{
    if ([sender.valueLable.text isEqualToString:@"非保本型"]) {
        TMGNotePresentViewController * noteVC = [TMGNotePresentViewController new];
        noteVC.note = @"黄金口袋金价实时参考上海黄金交易所和国际金价，不对金价的涨跌负责。由于金价下跌造成的亏损，需要用户自己承担";
        noteVC.titleString = @"小提示";
        [self presentViewController:noteVC animated:NO completion:nil];
//        [SVProgressHUD showInfoWithStatus:@"黄金口袋金价实时参考上海黄金交易所和国际金价，不对金价的涨跌负责。由于金价下跌造成的亏损，需要用户自己承担"];
    }
}
- (void)onSlectedBuyButton{
    TMGBuyGoldViewController * vc = [[TMGBuyGoldViewController alloc] initWithGoldType:TMGBuyGoldTypeGreenHand];
    vc.model = self.detailModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)onSlectedFlowInButton{
    //流动金转入
    TMGBuyGoldViewController * vc = [[TMGBuyGoldViewController alloc] initWithGoldType:TMGBuyGoldTypeGreenHand];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)sendGoodDetailReqeust{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/getGoodsDetails"];
    //    if ([STUserManger defult].userID.length) {
    //        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    //    }
    //    if ([STUserManger defult].token.length) {
    //        [dic setObject:[STUserManger defult].token forKey:@"token"];
    //    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.detailModel = [TMGProductDetailModel mj_objectWithKeyValues:dataDic];
                                                 self.detailModel.cate = self.model.cate.description;
                                                 [self configSubView];
                                                 [self reloadData];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendGoodPeopleBuyReqeust{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/goods/buyGoodsNumbers"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (self.model.goodiID.description.length) {
        [dic setObject:self.model.goodiID forKey:@"gid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 self.userArray = [NSMutableArray new];
                                                 for (NSDictionary * modelDic in array) {
                                                     TMGBuyUserModel * model = [TMGBuyUserModel mj_objectWithKeyValues:modelDic];
                                                     [self.userArray addObject:model];
                                                 }
                                                 if (self.detailModel) {
                                                     [self reloadData];
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

